//
//  DMPublishViewController.swift
//  DM_新浪微博
//
//  Created by Damon.JiAo on 16/3/4.
//  Copyright © 2016年 Demon_JiAo. All rights reserved.
//

import UIKit
import SnapKit

class DMPublishViewController: UIViewController ,UITextViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    /// 用来记录底部toolBar的约束
    var bottomConstrant:Constraint?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.whiteColor()
        
        /** 利用监听 -- 观察键盘弹出之后的事件 -- （！！很重要注意） */
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "changToolBarFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        setNavItem()
        
        setTextView()
        
        setupToolBar()
    }
    
    /** 设置nav */
    private func setNavItem(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "publish")
        
        navigationItem.rightBarButtonItem?.enabled = false
        
        //  设置基本属性
        let titleLabel = UILabel(frame: CGRectMake(0,0,200,44))
        
        titleLabel.numberOfLines = 0
        
        titleLabel.textAlignment = .Center
        
        let str = "发送微博\n\(DMUserViewModel.shareInstance.model?.screen_name ?? "")"
        /** 完成最主要的（最新的设置Label属性） */
        let attribute = NSMutableAttributedString(string: str)
        
        attribute.addAttributes([NSFontAttributeName:UIFont.systemFontOfSize(15)], range: NSMakeRange(0, 4))
        
        attribute.addAttributes([NSFontAttributeName:UIFont.systemFontOfSize(13),NSForegroundColorAttributeName:UIColor.orangeColor()], range: NSMakeRange(4, str.characters.count - 4))
        
        // 等效于  titleLabel.text = str
        titleLabel.attributedText = attribute
        
        navigationItem.titleView = titleLabel
        
    }
    
    /** 设置TextView */
    private func setTextView(){
        
        /*
        *   1.自己直接添加Label 
        *   2.自己绘画
        */
        
        /** 添加视图 */
        view.addSubview(textView)
        
        textView.frame = view.frame
        
        textView.holderString = "我的天！这么神奇？"
        
        textView.font = UIFont.systemFontOfSize(15)
        
        textView.delegate = self
        
        /** 滚动textView时，让键盘消失 */
        textView.alwaysBounceVertical = true
        textView.keyboardDismissMode = .OnDrag
        
        /** 添加视图 */
        textView.addSubview(photoView)
        
        photoView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(textView.snp_center)
            make.width.equalTo(KUIScreenWidth - 2*10)
            make.height.equalTo(KUIScreenWidth - 2*10)
        }
        
    }
    
    /** 底部添加toolBar */
    private func setupToolBar(){
        
        toolBar.backgroundColor = UIColor.lightGrayColor()
        
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "choosePicture"],
        ["imageName": "compose_mentionbutton_background"],
        ["imageName": "compose_trendbutton_background"],
        ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
        ["imageName": "compose_addbutton_background"]]
        
        ///     定义一个数值 来接受items
        var items = [UIBarButtonItem]()
        
        for setting in itemSettings{
            
            //  自定义button
            let button = UIButton(type: UIButtonType.Custom)
            
            button.setImage(UIImage(named: setting["imageName"]!), forState: UIControlState.Normal)
            
            let imageName = setting["imageName"]!
            button.setImage(UIImage(named: "\(imageName)_highlighted"), forState: UIControlState.Highlighted)
            
            button.sizeToFit()
            
            
            if let action = setting["action"]{
                
                button.addTarget(self, action:Selector(action), forControlEvents: UIControlEvents.TouchUpInside)
                
            }
            //     赋值给UIBarButtonItem
            let item = UIBarButtonItem(customView: button)
            
            //     item 添加到toolBar上  一定要自己定义一个数组
            items.append(item)
            //     添加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            
        }
        
        items.removeLast()
        toolBar.items = items
        
        view.addSubview(toolBar)
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(view.snp_bottom)
            
            make.height.equalTo(40)
        }
    }
    
    /** 选择图片按钮 */
    @objc private func choosePicture(){
        
        /*
        case PhotoLibrary -- 相册
        case Camera         -- 相机
        case SavedPhotosAlbum -- 保存的相册
        */
        //  判断一下能否访问相册
        if UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary){
            
            //  如果可以访问则--跳转页面
            let picker = UIImagePickerController()
            
            // UIImagePickerController 如果你要 使用 相机的画,一定要注意修改成 Camera
            picker.sourceType = .PhotoLibrary
            
            picker.delegate = self
            
            presentViewController(picker, animated: true, completion: nil)
            
        }
        
    }
    //MARK: -- 表情按钮
    @objc private func inputEmoticon(){
        
        /*
            1.先设计界面
            2.添加数据
        */
        
        textView.resignFirstResponder()
     
        if textView.inputView == nil{
            textView.inputView = emotionView
        }else{
            textView.inputView = nil
        }

        textView.becomeFirstResponder()
        
    }
    
    //MARK:-- 懒加载
    ///   文字视图懒加载
    private lazy var textView:DMTextView = DMTextView()
    
    ///   toolBar的懒加载
    private lazy var toolBar:UIToolbar = UIToolbar()
    
    ///   图片选择容器
    private lazy var photoView : DMPhotoView = {
        
        let photo = DMPhotoView()
        
        weak var weakself = self
        
        photo.closure = {[unowned self] ()->() in
            
            weakself!.choosePicture()

        }
        
       return photo
    }()
    
    ///   表情的View视图
    private lazy var emotionView:DMEmotionView = {
        let emotion = DMEmotionView()
        
        emotion.backgroundColor = UIColor.grayColor()

        emotion.frame.size = CGSizeMake(KUIScreenWidth,216)
        return emotion
    }()
    
    /** 监听键盘动作之后--调用方法 */
    func changToolBarFrame(noti:NSNotification){
        
        /**  */
//        print(noti.userInfo)
        
        /*Optional(
        [UIKeyboardFrameBeginUserInfoKey: NSRect: {{0, 736}, {414, 271}}, 
        UIKeyboardCenterEndUserInfoKey: NSPoint: {207, 871.5},
        UIKeyboardBoundsUserInfoKey: NSRect: {{0, 0}, {414, 271}},
        UIKeyboardFrameEndUserInfoKey: NSRect: {{0, 736}, {414, 271}},
        UIKeyboardAnimationDurationUserInfoKey: 0.25, 
        UIKeyboardCenterBeginUserInfoKey: NSPoint: {207, 871.5}, 
        UIKeyboardAnimationCurveUserInfoKey: 7, UIKeyboardIsLocalUserInfoKey: 1])
        */
        
        if let info = noti.userInfo{
            let endnFrame = info[UIKeyboardFrameEndUserInfoKey]?.CGRectValue
            
            if endnFrame?.origin.y == KUIScreenHeight{
                
                toolBar.snp_updateConstraints(closure: { (make) -> Void in
                    self.bottomConstrant = make.bottom.equalTo(view.snp_bottom).constraint
                })
                
            }else{
                
                toolBar.snp_updateConstraints(closure: { (make) -> Void in
                    self.bottomConstrant = make.bottom.equalTo(view.snp_bottom).offset(-endnFrame!.size.height).constraint
                })
                
            }
            
            ///     取出键盘动画时间
            let durantion = info[UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
            
            UIView.animateWithDuration(durantion, animations: { () -> Void in
                
                self.toolBar.layoutIfNeeded()
            })
            
        }
        
    }
 
    /** 将键盘监听移除 */
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardDidChangeFrameNotification, object: nil)
    }
    
    /** 返回按钮 */
    @objc private func dismiss(){
       
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    /** 发送按钮 */
    @objc private func publish(){
        print("发送")
    }
    
}

//MARK：--  选择图片加载工作
extension DMPublishViewController{
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        photoView.addImages(image)
        
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}

//MARK:-- 完成TextView文字的填充
extension DMPublishViewController{
    
    func textViewDidChange(textView: UITextView) {
        if textView.hasText(){
            self.textView.holderString = ""
            
        }else{
            self.textView.holderString = "我的天！这么神奇吗"
        }
        
        self.textView.setNeedsDisplay()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    
}

